<template>
  <div>
    <div>
      <div class="search flex flex_between" style="height: 2.5rem;width: 100%;color: #fff;background: #2196f3;">
        <div class="toHistory" style="padding: 0.5rem 1rem;width: 13%" v-on:click="toMain()">
          <i class="fa fa-chevron-left"></i>
        </div>

        <div class="for-search flex flex_between flex_vertical_center"  @click="toMapSearch()" style="width: 87%">
          <input style="background: #fff;height: 1.8rem!important;font-size: 0.9rem" type="text" placeholder="请输入搜索地址">
          <i class="fa fa-search fa-choosed for-search" style="margin-right: 2rem"></i>
        </div>

      </div>
      <div style="width:100%;height: 100%" id="container"></div>
      <div class="scroll">
        <div style="text-align: center;padding: 1rem 0 0.5rem 0;font-size: 1rem;border-bottom: 2px solid #eee">请选择地址</div>
        <div class="content" id="choose" style="padding: 1rem;padding-top: 0.3rem;margin-bottom: 1rem">
          <div style="border-bottom: 3px solid #f1f1f1" class="address-choose" v-for="near in near_post.nearPois" v-on:click="choosePost(near)">
            <div class="address">
              <p>{{near.name}}</p>
              <p style="color: #9a9a9a;font-size: 0.75rem">{{near.address}}</p>
            </div>
          </div>
        </div>
      </div>
      <input type="hidden" name="province_id" id="province_id">
      <input type="hidden" name="city_id" id="city_id">
      <input type="hidden" name="area_id" id="area_id">
      <p style="text-align:left;padding:0.3rem 1rem;background:#fff3dc;color: salmon;position: fixed;left: 0;right: 0;bottom: 3rem">
        <i style="margin-right: 0.3rem" class="fa fa-map-marker"></i>已选地址：{{position_address}}
      </p>
      <button type="button" class="choose_end mui-btn-blue buttom_sure" v-on:click="sureEnd()">完成</button>
      这是地图选取地址组件
  </div>
  </div>
</template>

<script>
  import city3 from '../../../assets/js/city.data-3';
  import Loading from "../../../components/loading";
  import { Tmap } from '../../../assets/js/map';
  var geocoder, map, marker ,address  ,provice,city,district = null;
  export default {
    components: {Loading},
    name: "map-choose-address",
    props:['mapAddress','region'],
    data(){
      return{
        near_post:'',
        center:'',
        addressComponents:'',
        lat:'',
        lng:'',
        position_address:'无',
        area_info:'',
        province_id:'',
        city_id:'',
        area_id:'',
        endStaus:0,

      }
    },
    mounted(){
      //计算地图全屏高度
      var height = $(document).height();
      $('#container').css('height',height);

      this.center = new qq.maps.LatLng('30.462959','114.419449');

      //获取当前地址的经纬度
      this.initLatLng();

    },
    methods:{
      initLatLng(){
        this.area_position = this.mapAddress.area_position ||'';
        this.area_info = this.mapAddress.area_info;
        this.province_id=this.mapAddress.province_id;
        this.city_id = this.mapAddress.city_id;
        this.area_id = this.mapAddress.area_id;
        var addressDetail = this.area_info + ' '+this.mapAddress.address;
        if(!this.isEmpty(this.area_position)){
          this.lat = this.area_position.split(',')[0];
          this.lng = this.area_position.split(',')[1];
          this.center = new qq.maps.LatLng(this.lat, this.lng);
          this.endStaus = 0;
        }else if(this.isEmpty(addressDetail)){
          //获取用户当前地址
          this.initCurrentAddress();
        }else {
          //地址和经纬度之间进行转换服务
          this.initMapLatLngBuyAddress();
        }
      },

      //定位当前地址
      initCurrentAddress(){
        var _self = this;
        var geolocation = new qq.maps.Geolocation("RHHBZ-K26W6-CPISS-ENGXG-HVCRS-QJFQT", "qds");
        var options = {timeout: 8000};
        geolocation.getLocation(showPosition, showErr, options)
        function showPosition(position) {
          this.province = position.province;
          this.city = position.city;
          if(this.city != undefined && this.city != null && this.city != ''){
            this.region = this.city;
            _self.$emit('getregion', this.region)
          }
          this.area = position.district == undefined || position.district == null || position.district ==  ''?'':position.district;
          this.lat = position.lat;
          this.lng = position.lng;
          this.center = new qq.maps.LatLng(this.lat, this.lng);
          this.endStaus = 0;
          marker.setMap(null);
          map.setCenter(this.center);
          marker = new qq.maps.Marker({
            map:map,
            position: this.center
          });
        };
        //定位失败直接调地图
        function showErr() {
          this.lat='30.462959';
          this.lng = '114.419449';
          this.center = new qq.maps.LatLng(this.lat, this.lng);
          this.endStaus = 0;
          marker.setMap(null);
          map.setCenter(this.center);
          marker = new qq.maps.Marker({
            map:map,
            position: this.center
          });
        };
      },


      //根据地址 获取地图对应经纬度
      initMapLatLngBuyAddress(){
        geocoder = new qq.maps.Geocoder({
          //设置服务请求成功的回调函数
          complete: function(result) {
            this.lat = result.detail.location.lat;
            this.lng = result.detail.location.lng;
            this.center = new qq.maps.LatLng(this.lat, this.lng);
          },
          //若服务请求失败，则运行以下函数
          error: function() {

          }
        });
        //如果没有经纬度 那么 按照店铺地址获取经纬度
        geocoder.getLocation(address);
      },

      toMain(){
        this.$emit('mapSearch', 0)//直接显示主页面
      },

      sureEnd:function () {
        //将所获得数据 保存到缓存
        if(!this.endStaus){
          /*alert('请选择所需地址');*/
          this.$toast.warning('请选择所需地址');
          return;
        }

        this.mapAddress.area_position = this.center.lat+','+this.center.lng;
        this.mapAddress.address = this.position_address;
        this.mapAddress.area_info = this.area_info;
        this.mapAddress.province_id = this.province_id;
        this.mapAddress.city_id = this.city_id;
        this.mapAddress.area_id = this.area_id;


        //将所选地址相关信息 传递给父组件
        this.$emit('getMapAddress', this.mapAddress)//直接显示主页面
        this.$emit('mapSearch', 0)//直接显示主页面

      },
      choosePost:function (obj) {
        this.endStaus = 1;
        if(marker != undefined && marker != null && marker != ''){
          marker.setMap(null);
        }
        this.position_address = obj.name;
        this.center = obj.latLng;

        //绑定单击事件添加参数
        qq.maps.event.addListener(map, 'click', function(event) {
          this.address = '';
          if(marker != undefined && marker != null && marker != ''){
            marker.setMap(null);
          }
          var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
          _self.center = latLng;
          this.endStaus = 0;

        });
      },
      toMapSearch(){
        this.$emit('mapSearch', 2)//直接显示主页面
      }
    },
    //监听 1：中心地点改变  2：附近地址改变  3:省市区发生变化
    watch:{
      //1
      center:{
        handler(curVal,oldVal){
          var _self = this;
          var myOptions = {
            zoom: 16,
            center: curVal,
            mapTypeId: qq.maps.MapTypeId.ROADMAP
          }


          map = new qq.maps.Map(document.getElementById("container"), myOptions);
          //添加监听事件
          //点击地图获取点击地点的地址和坐标
          geocoder = new qq.maps.Geocoder({
            complete : function(result){
              _self.near_post = result.detail;
              _self.addressComponents = result.detail.addressComponents;
            }
          });

          marker = new qq.maps.Marker({
            map:map,
            position: _self.center
          });

          _self.area_position = curVal.lat+','+curVal.lng;
          //获取输入框的经纬度
          var latLng = new qq.maps.LatLng(curVal.lat, curVal.lng);
          //对指定经纬度进行解析
          geocoder.getAddress(latLng);
          //设置服务请求成功的回调函数
          geocoder.setComplete(function(result) {
            if(!_self.isEmpty(result.detail.addressComponents.city)){
              _self.shopCity = result.detail.addressComponents.city;
            }
            _self.near_post = result.detail;
            _self.addressComponents = result.detail.addressComponents;
            var obj = _self.addressComponents;
            if(obj!=undefined && obj != null && obj != ''){
              var provice = obj.province
              var city = obj.city;
              var district = obj.district;
              if(provice!=undefined&&provice!=null && provice != ''){
                _self.area_info = provice;
              }
              if(city != undefined && city != null && city != ''){
                _self.area_info +=' '+ city;
              }
              if(district != undefined && district != null && district != ''){
                _self.area_info +=' '+ district;
              }
            }
          });
          //若服务请求失败，则运行以下函数
          geocoder.setError(function() {
            return null;
          });

          //绑定单击事件添加参数
          qq.maps.event.addListener(map, 'click', function(event) {
            this.address = '';
            if(marker != undefined && marker != null && marker != ''){
              marker.setMap(null);
            }
            var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
            _self.center = latLng;

          });
        },
        deep:true
      },



      //3  这个不需要深层次监听
      area_info(curVal,oldVal){
        var _self = this;

        var cityData3 = city3.cityData3;

        if(cityData3 == undefined || cityData3 == null || cityData3 == '' || cityData3.length <=0){
          return;
        }
        for(var i=0;i<cityData3.length;i++){
          var data = cityData3[i];
          if(data.text == provice){
            _self.province_id = data.value
            var children = data.children;
            if(children != undefined && children != null && children != '' && children.length > 0){
              for(var j = 0;j<children.length;j++){
                if(children[j].text == city){
                  _self.city_id = children[j].value
                  children = children[j].children;
                  if(children != undefined && children != null && children != '' && children.length > 0){
                    for(var m =0;m<children.length;m++){
                      if(children[m].text == district){
                        _self.area_id = children[m].value
                        break;
                      }else if(m >= children.length -1){
                        _self.area_id = _self.city_id;
                      }
                    }
                  }else {
                    _self.area_id = _self.city_id;
                  }
                  break;
                }else if(j >= children.length -1){
                  _self.city_id = _self.area_id = _self.province_id;
                }
              }
            }else {
              _self.city_id = _self.area_id = _self.province_id;
            }
            break;
          }
        }
      },
    },
  }
</script>

<style scoped>
  /*@import 'http://cdn.bootcss.com/material-design-icons/3.0.1/iconfont/material-icons.css';*/
  .search{
    position: fixed;font-size: 1rem;z-index: 5;display: flex;display: -webkit-flex;align-items: center;-webkit-align-items: center;
  }
  input[type =text]{
    border: none;
  }
  .scroll{
    overflow-y: scroll;
    background: #f1f1f1;
    position: fixed;
    /* top: 4.1rem; */
    left: 0;
    right: 0;
    bottom: 3rem;
    height: 14rem;
  }
  .buttom_sure{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    height: 3rem;
    border: none;
    background: salmon;
    color: #fff;
  }
  .address{
    padding: 1rem;
  }

  .address-choose{
    background: #fff;
    border-radius: 8px;
    margin-bottom: 0.4rem;
  }

  #choose{
    padding: 1rem;
    padding-top: 0;
  }
  a{
    color: #fff;
  }

  .header{
    width: 100%;
    padding: 0.5rem;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    align-items: center;
    -webkit-align-items: center;
    border-bottom: 1px solid #c3c3c3;
    background: #fff;
    position: relative;
  }
  .header img{
    width: 1.25rem;
    height: 1.25rem;
  }
</style>
